<!--
  * 登录
  *
  * @Author:    1024创新实验室-主任：卓大
  * @Date:      2022-09-12 22:34:00
  * @Wechat:    zhuda1024
  * @Email:     lab1024@163.com
  * @Copyright  1024创新实验室 （ https://1024lab.net ），Since 2012
  *
-->
<template>
  <div class="login-container">
    <div class="box-item desc">
      <div class="welcome">
        <p>欢迎登录 SmartAdmin V3</p>
        <p class="sub-welcome">「高质量代码、简洁、安全」的开发平台</p>
      </div>
      <img class="welcome-img" :src="leftBg2"/>
    </div>
    <div class="box-item login">
      <div class="login-account">
        <div class="login-account-card show">
          <div class="login-title">账号登录</div>
          <el-form
              ref="formRef"
              class="login-form"
              :model="loginForm"
              :rules="rules"
          >
            <el-form-item prop="loginName">
              <el-input
                  size="large"
                  v-model.trim="loginForm.loginName"
                  placeholder="请输入用户名"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                  v-model="loginForm.password"
                  show-password
                  autocomplete="on"
                  size="large"
                  :type="showPassword ? 'text' : 'password'"
                  placeholder="请输入密码：至少三种字符，最小 8 位"
              />
            </el-form-item>
            <el-form-item prop="captchaCode">
              <div style="display: flex; align-items: center">
                <el-input
                    class="captcha-input"
                    size="large"
                    v-model.trim="loginForm.captchaCode"
                    placeholder="请输入验证码"
                />
                <img
                    class="captcha-img"
                    :src="captchaBase64Image"
                    @click="getCaptcha"
                    alt=""
                />
              </div>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="rememberPwd">记住密码</el-checkbox>
              <span>( 账号：admin, 密码：123456)</span>
            </el-form-item>
            <el-form-item>
              <div class="btn" @click="onLogin">登录</div>
            </el-form-item>
          </el-form>
        </div>
        <div class="more">
          <div class="title-box">
            <p class="line"></p>
            <p class="title">其他方式登录</p>
            <p class="line"></p>
          </div>
          <div class="login-type">
            <WeChatSignIn v-slot="{ wechatLogin }">
              <img @click="wechatLogin" :src="wechatIcon" width="40px" height="40px" alt="微信登录图标" />
            </WeChatSignIn>
            <AlipaySignIn v-slot="{ alipayLogin }">
              <img @click="alipayLogin" :src="aliIcon" alt=""/>
            </AlipaySignIn>
            <GitHubSignIn v-slot="{ GitHubLogin }">
              <img :src="githubIcon" @click="GitHubLogin" alt=""/>
            </GitHubSignIn>
            <GiteeSignIn v-slot="{ GiteeLogin }">
              <img :src="giteeIcon" @click="GiteeLogin" alt=""/>
            </GiteeSignIn>
            <img :src="qqIcon" alt=""/>
            <img :src="weiboIcon" alt=""/>
            <FeishuSignIn v-slot="{ FeishuLogin }">
              <img :src="feishuIcon" @click="FeishuLogin" alt=""/>
            </FeishuSignIn>
            <GoogleSignIn>
              <div>
                <div
                    id="g_id_onload"
                    data-client_id="515428572517-rnue9oq3r9ev2q9f843516cuinmcru2d.apps.googleusercontent.com"
                    data-context="signin"
                    data-ux_mode="popup"
                    data-callback="googleCallback"
                    data-auto_prompt="false"
                ></div>
                <div
                    class="g_id_signin"
                    data-type="icon"
                    data-shape="circle"
                    data-theme="filled_black"
                    data-text="signin"
                    data-size="medium"
                    data-locale="zh-CN"
                ></div>
              </div>
            </GoogleSignIn>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import {onMounted, onUnmounted, reactive, ref} from 'vue'
import {useRouter, useRoute} from 'vue-router'
import {loginApi} from '@/api/system/login/login-api'
import leftBg2 from '@/assets/login/left-bg2.png'
import wechatIcon from '@/assets/login/wechat-icon.png'
import aliIcon from '@/assets/login/ali-icon.png'
import githubIcon from "@/assets/login/github.png";
import qqIcon from '@/assets/login/qq-icon.png'
import weiboIcon from '@/assets/login/weibo-icon.png'
import feishuIcon from '@/assets/login/feishu-icon.png'
import giteeIcon from "@/assets/login/gitee.png"
import {localSave} from '@/utils/local-util.ts'
import GoogleSignIn from '@/components/GoogleLogin/index.vue'
import AlipaySignIn from '@/components/AlipayLogin/index.vue'
import FeishuSignIn from '@/components/FeishuLogin/index.vue'
import GitHubSignIn from '@/components/GitHubLogin/index.vue'
import GiteeSignIn from "@/components/GiteeLogin/index.vue"
import WeChatSignIn from '@/components/WechatLogin/index.vue'
import {ElMessage} from "element-plus";
const route = useRoute()
//--------------------- 登录表单 ---------------------------------

const loginForm = reactive({
  loginName: 'admin',
  password: '123456',
  captchaCode: '',
  captchaUuid: '',
  loginDevice: "PC",
})
const rules = {
  loginName: [{required: true, message: '用户名不能为空'}],
  password: [{required: true, message: '密码不能为空'}],
  captchaCode: [{required: true, message: '验证码不能为空'}],
}
const showPassword = ref(false)
const router = useRouter()
const formRef = ref()
const rememberPwd = ref(false)

onMounted(() => {
  document.onkeyup = (e) => {
    if (e.keyCode == 13) {
      onLogin()
    }
  }
})

onUnmounted(() => {
  document.onkeyup = null
})

//登录
async function onLogin() {
  formRef.value.validate().then(async () => {
    const res = await loginApi.login(loginForm)
    if (res.code == 0) {
      ElMessage.error(res.data.message)
      await getCaptcha()
    } else {
      localSave(
          "smart_admin_user_token",
          res.data.token ? res.data.token : '',
      )
      ElMessage.success('登录成功')
      //更新用户信息到pinia
      localStorage.setItem('name', res.data.user.username)
      await router.push('/home')
    }
  })
}
//--------------------- 验证码 ---------------------------------

const captchaBase64Image = ref('')

async function getCaptcha() {
  try {
    let captchaResult = await loginApi.getCaptcha()
    captchaBase64Image.value = captchaResult.data.captchaBase64Image
    loginForm.captchaUuid = captchaResult.data.captchaUuid
  } catch (e) {
    console.log(e)
  }
}

onMounted(async () => {
  await getCaptcha()
  // 获取公众号二维码
  sessionStorage.setItem('myId', '')
  // 👇 页面加载时检测是否是支付宝,飞书授权回调，携带 token 和用户信息
  const token = route.query.token
  const email = route.query.email
  const avatar = route.query.avatar
  const name = route.query.name

  if (token) {
    // ✅ 存储登录信息
    localStorage.setItem('smart_admin_user_token', token)
    localStorage.setItem('userInfo', JSON.stringify({email, avatar, name}))
    localStorage.setItem('user', JSON.stringify(name))
    localStorage.setItem('avatar', avatar)
    // ✅ 重定向到首页或你想去的页面
    await router.replace('/home')
  }
})
</script>
<style lang="less" scoped>
@import './login.less';
</style>
